//
//  YCTitleSegmentView.m
//  TitleContent
//
//  Created by 唐可雄 on 2019/7/18.
//  Copyright © 2019 swustyc. All rights reserved.
//

#import "YCTitleSegmentView.h"

@interface YCTitleSegmentView ()

@property (nonatomic, strong) UISegmentedControl *segmentControl;

@end

@implementation YCTitleSegmentView

#pragma mark - Super-Sub View

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];
    
    if (newSuperview) {
        [self configView];
    }
}

#pragma mark - View Config

- (void)configView {
    [self addSegmentControl];
    [self addSeparatorView];
}

- (void)addSegmentControl {
    self.segmentControl = [[UISegmentedControl alloc] init];
    
    [self.segmentControl addTarget:self action:@selector(segmentValueDidChange:) forControlEvents:UIControlEventValueChanged];
    
    self.segmentControl.tintColor = self.config.tintColorSegment;
    
    [self loadData];
    self.segmentControl.selectedSegmentIndex = 0;
    
    self.segmentControl.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:self.segmentControl];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.segmentControl attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.segmentControl attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
}

#pragma mark - Segment Control

- (void)segmentValueDidChange:(UISegmentedControl *)segmentControl {
    if ([self.delegate respondsToSelector:@selector(titleView:didSelectAtIndex:)]) {
        [self.delegate titleView:self didSelectAtIndex:segmentControl.selectedSegmentIndex];
    }
}

#pragma mark - YCTitleView

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    [self.segmentControl setSelectedSegmentIndex:selectedIndex];
}

#pragma mark - Load

- (void)reloadData {
    [self.segmentControl removeAllSegments];
    
    [self loadData];
}

- (void)loadData {
    NSUInteger number = [self.dataSource numberOfTitlesInTitleView:self];
    if ([self.dataSource respondsToSelector:@selector(titleSegmentView:titleAtIndex:)]) {
        for (int i = 0; i < number; i++) {
            [self.segmentControl insertSegmentWithTitle:[self.dataSource titleSegmentView:self titleAtIndex:i] atIndex:i animated:NO];
        }
    } else if ([self.dataSource respondsToSelector:@selector(titleSegmentView:imageAtIndex:)]) {
        for (int i = 0; i < number; i++) {
            [self.segmentControl insertSegmentWithImage:[self.dataSource titleSegmentView:self imageAtIndex:i] atIndex:i animated:NO];
        }
    }
}

@end
